﻿using System.Collections;
using System.Collections.Generic;

namespace Borg
{
    public class LogBuffer : IEnumerable<LogEventArgs>
    {
        private readonly Queue<LogEventArgs> _logbuffer;
        private int _size;

        public int Count
        {
            get { return _logbuffer.Count; }
        }

        public int Size
        {
            get { return _size; }
            set
            {
                if (value > 0)
                {
                    if (_size == 0)
                        Runtime.LogEvent += RuntimeLogEvent;
                    else if (_size > value)
                        for (var i = _logbuffer.Count; i > value; i--)
                            _logbuffer.Dequeue();
                }
                else if (_size > 0)
                {
                    Runtime.LogEvent -= RuntimeLogEvent;
                    _logbuffer.Clear();
                }

                _size = (value >= 0) ? value : 0;
            }
        }

        public LogBuffer(int size)
        {
            _size = size;
            _logbuffer = new Queue<LogEventArgs>(size);

            if (size > 0)
                Runtime.LogEvent += RuntimeLogEvent;
        }

        public IEnumerator<LogEventArgs> GetEnumerator()
        {
            return _logbuffer.GetEnumerator();
        }

        private void RuntimeLogEvent(object sender, LogEventArgs args)
        {
            if (_logbuffer.Count == _size)
                _logbuffer.Dequeue();

            _logbuffer.Enqueue(args);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

